package com._430haus.VLC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;

import com._430haus.Video.Video;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class VLCListenerClientThread extends Thread {
	
	private Socket socket;

	private PrintWriter out;

	private BufferedReader in;
	
	public VLCListenerClientThread(final Socket socket) {
		
		this.socket = socket;
		
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {

		}
		
	}
	
	@Override
	public void run() {
		//add hang detection in this and kill it 
		//possibly add this feature to VLCListener
		//keep list of threads
		//threads have time running property
		//time running > x seconds, kill?
		
		String get = null;
		
		String line;
		try {
			while((line = in.readLine()) != null){
				if(line.contains("GET /?")){
					get = line.substring(line.indexOf('{'), line.lastIndexOf('}') + 1);
					//in.close();
					break;
				}
				
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		} 

		if(get != null){
			
			if(get.contains("KILLVLC430HAUS")){
				
				VLCLauncher.killVLC();
				
			}else{
			
				Gson gson = new GsonBuilder().create();
		        Video v = null;
				try {
					v = gson.fromJson(URLDecoder.decode(get, "UTF8"), Video.class);
				} catch (JsonSyntaxException | UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				
				if(v != null){
					System.out.println(v.getLocation());
		        
					out.write("{error: \"");
				
					try {
						VLCLauncher.launchVideo(v.getLocation());
						out.write("None");
					} catch (IOException | InterruptedException e) {
						out.write(e.getMessage());
					}
					
					out.write("\"}");
				}
				
			}
		}
		out.close();
	}

}
